from django.shortcuts import render,redirect
from django import forms
# 导入app01的models包
from app01 import models
# 导入正则表达式包，校验方法一
from django.core.validators import RegexValidator
# 导入钩子校正方法，校验方法二
from django.core.exceptions import ValidationError
# BootStrapModelForm导入
from app01.utils.bootstrap import BootStrapModelForm
# 分页组件封装
from app01.utils.pagination import Pagination
# form导入
from app01.utils.form import UserModelForm,PrettyModelForm,PrettyEditModelForm


# Create your views here.
# def depart_list(request):
#     """ 部门列表 """
#     # 去数据库中获取所有部门信息
#     # 得到一个queryset的列表对象[对象,对象,对象]
#     queryset = models.Department.objects.all()
#
#     # 引用封装好的分页组件
#     page_object = Pagination(request, queryset,page_size=5)
#     context = {
#         "queryset": page_object.page_queryset,
#         "page_string": page_object.html(),
#     }
#
#     # 把queryset当作参数传递给前端，在前端的html中做渲染for循环queryset中的对象
#     return render(request,'depart_list.html',context)
#
# def depart_add(request):
#     """ 新建部门 """
#     if request.method == 'GET':
#         return render(request,'depart_add.html')
#     # 获取post表单数据
#     title = request.POST.get("title")
#     # 把得到的数据保存到数据库中
#     models.Department.objects.create(title=title)
#     # 通过导入redirect包功能重定向到部门列表页面
#     return redirect("/depart/list/")
#
# def depart_delete(request):
#     """删除部门"""
#     # 通过GET方式获取要删除的ID
#     # href="/depart/delete/?nid={{ obj.id }}
#     nid = request.GET.get("nid")
#     # 删除，通过Department函数找到要删除的ID
#     models.Department.objects.filter(id=nid).delete()
#
#     # 重定向到部门列表
#     return redirect("/depart/list/")
#
# def depart_edit(request,nid):
#     """修改部门"""
#     if request.method == 'GET':
#         # 点击编辑事件跳转到edit页面
#         # http://localhost:8000/depart/int(id)/edit/
#         # 也就是说通过url链接把数据库中的ID值带过来
#         row_object = models.Department.objects.filter(id=nid).first()
#         # print(row_object.id,row_object.title)
#         # 把值当做参数传递到edit页面
#         return render(request,'depart_edit.html',{'row_object':row_object})
#
#     # 提交按钮触发POST请求，获得需要更新的数据
#     title = request.POST.get("title")
#     # 根据ID找到数据库中的数据并更新
#     # 如有多个值需要修改在.update(title=title)括号中添加
#     models.Department.objects.filter(id=nid).update(title=title)
#     # 重定向到list页面
#     return redirect("/depart/list/")


# def user_list(request):
#     """ 用户管理 """
#     # 获取数据库中用户的数据，得到一个[对象1，对象2，对象3]
#     queryset = models.UserInfo.objects.all()
#     """ 用python的语法加djongo框架获取数据
#     for obj in queryset:
#         # 这里如果不对obj.create_time进行处理得到是一个这个格式的时间日期
#         # 1 刘德华 1998.68 2023-01-11 00:00:00+00:00 <class 'datetime.datetime'>
#         # 2 张惠妹 1008.68 2024-01-11 00:00:00+00:00 <class 'datetime.datetime'>
#         # print(obj.id,obj.name,obj.account,obj.create_time,type(obj.create_time))
#         # 这里性别也要处理，不处理默认显示的1or2,使用get_gender_display()方法(djongo封装)，得到是gender男或女
#         # 1 刘德华 1998.68 2023-01-11 1
#         # 2 张惠妹 1008.68 2024-01-11 2
#         # obj.depart.title这里不要写depart_id，因为depart是一个对象，这样写获取到的是对应的部门名称而不是部门ID，
#         # 去关联的表中取到title对象
#         print(obj.id,obj.name,obj.account,obj.create_time.strftime("%Y-%m-%d"),
#               obj.get_gender_display(),obj.depart.title)
#     """
#     # 将封装好的分页组件拿过来
#     page_object = Pagination(request,queryset,page_size=15)
#     context = {
#         "queryset": page_object.page_queryset,
#         "page_string": page_object.html(),
#     }
#     # 将数据作为参数传递到前端
#     return render(request,'user_list.html', context)
#
# def user_add(request):
#     """ 添加用户 原始方法"""
#     # GET请求
#     if request.method == 'GET':
#         context = {
#             'gender_choices': models.UserInfo.gender_choices,
#             'depart_list': models.Department.objects.all(),
#         }
#         # 把性别和部门数据作为字典参数传递给前端做select选择
#         """
#         gender_choices = (
#             (1, "男"),
#             (2, "女")
#         )
#         gender = models.SmallIntegerField(verbose_name="性别", choices=gender_choices)
#         """
#         return render(request,'user_add.html',context)
#     # POST请求,获取用户提交的数据
#     user = request.POST.get('user')
#     pwd = request.POST.get('pwd')
#     age = request.POST.get('age')
#     account = request.POST.get('ac')
#     ctime =request.POST.get('ctime')
#     gender = request.POST.get('gd')
#     depart_id = request.POST.get('dp')
#
#     # 把数据添加到数据库中
#     models.UserInfo.objects.create(name=user,password=pwd,age=age,
#                                    account=account,create_time=ctime,
#                                    gender=gender,depart_id=depart_id)
#     return redirect("/user/list/")
#
# """ 从这里开始，基于ModelForm的示例 """
# # class UserModelForm(BootStrapModelForm):
# #     name = forms.CharField(
# #         min_length=4,
# #         label="用户名",
# #         widget=forms.TextInput(attrs={"class": "form-control"})
# #     )
# #
# #     class Meta:
# #         model = models.UserInfo
# #         fields = ["name","password","age","account","gender","create_time","depart"]
# #     # 已继承BootStrapModelForm类，下面的代码不用写了。继承bootstrap样式
# #     # def __init__(self, *args, **kwargs):
# #     #     super().__init__(*args, **kwargs)
# #     #     # 循环ModelForm中的所有字段，给每个字段做widget插件，添加了class="form-control"
# #     #     for name,field in self.fields.items():
# #     #         # 加"placeholder": field.label，输入框显示提示信息
# #     #         field.widget.attrs = {"class": "form-control","placeholder": field.label}
#
# def user_model_form_add(request):
#     """" 添加用户（ModelForm版本）"""
#     if request.method == 'GET':
#
#         form = UserModelForm()
#         return render(request,'user_model_form_add.html',{'form':form})
#     # 用户POST提交数据，做数据校验 ，把UserModelForm实例化，得到form的数据，放在前端渲染
#     form = UserModelForm(data=request.POST)
#     # 数据正确则直接返回用户列表页面
#     if form.is_valid():
#         # 添加数据
#         form.save()
#         return redirect("/user/list/")
#     # 校验失败则提示错误信息
#     return render(request,'user_model_form_add.html',{'form':form})
#
# def user_edit(request,nid):
#     """ 编辑用户信息 """
#     # 根据ID去数据库获取要编辑的哪一行数据（对象）,这一行写在最外面，因为POST请求更新也会用到这个数据
#     row_object = models.UserInfo.objects.filter(id=nid).first()
#     if request.method == 'GET':
#         # 首先是GET请求，因为要把编辑用户的数据默认的写在输入栏中
#         form = UserModelForm(instance=row_object)
#         return render(request,'user_edit.html',{'form':form})
#     # POST请求,把修改的信息更新
#     form = UserModelForm(data= request.POST,instance=row_object)
#     # 校验正确
#     if form.is_valid():
#         # 默认保存的是用户输入的所有数据
#         form.save()
#         return redirect("/user/list/")
#     # 否则，把错误的信息显示在编辑用户页面
#     return render(request,'user_edit.html',{'form':form})
#
# def user_delete(request,nid):
#     models.UserInfo.objects.filter(id=nid).delete()
#     return redirect("/user/list/")

# def pretty_list(request):
#     """ 靓号管理 """
#     # 添加300条测试数据
#     # for i in range(300):
#     #     models.PrettyNum.objects.create(mobile="12345678909",price=19.9,level=1,status=1)
#
#     # -level,表示desc排序,按级别排序
#     # queryset = models.PrettyNum.objects.all().order_by('-level')
#     # return render(request,'pretty_list.html',{'queryset':queryset})
#     # 加搜索功能上面两行代码重写
#     # 先定义一个空字典，把搜索内容添加到空字典，有值传值，并把值传到前端搜索框显示出来，没值搜索所有
#     data_dict = {}
#     search_data = request.GET.get('q',"")
#     if search_data:
#         data_dict["mobile__contains"] = search_data
#
#     # 页码
#     """
#         <li><a href="?page=1">1</a></li>
#         <li><a href="?page=2">2</a></li>
#         <li><a href="?page=3">3</a></li>
#         <li><a href="?page=4">4</a></li>
#         <li><a href="?page=5">5</a></li>
#     """
#     queryset = models.PrettyNum.objects.filter(**data_dict).order_by("-level")
#     page_object = Pagination(request,queryset,page_size=15)
#     # page_queryset = page_object.page_queryset
#     # page_string = page_object.html()
#     context = {
#                "search_data":search_data,
#                "queryset": page_object.page_queryset,  # 分完页的数据
#                "page_string":page_object.html()   # 页码
#                }
#
#     # 根据用户想要访问的页码，计算出起止位置,默认第一页起
#     # page = int(request.GET.get('page', 1))
#     # page_size = 10  # 定义一个变量，便于修改一页多少数据
#     # start = (page - 1) * page_size
#     # end = page + page_size
#
#     # queryset = models.PrettyNum.objects.filter(**data_dict).order_by("-level")[page_object.start:page_object.end]
#     # 计算数据库总条数
#     # total_count = models.PrettyNum.objects.filter(**data_dict).order_by("-level").count()
#     # # 计算数据页数divmod(),python内置方法：取商取余91%10 =（9，1）
#     # total_page_count, div = divmod(total_count, page_size)
#     # if div:
#     #     # 数据库中获取值时，前取后不取，这里+1
#     #     total_page_count += 1
#     # 计算出，显示当前页的前5页和后5页
#     # plus = 5
#     # if total_page_count <= 2 * plus + 1:
#     #     # 数据较少
#     #     start_page = 1
#     #     end_page = total_page_count + 1
#     # else:
#     #     # 数据较多>11页时
#     #     # 当前页<5时（小极值）
#     #     if page <= plus:
#     #         start_page = 1
#     #         end_page = 2 * plus + 1
#     #     else:
#     #         # 当前页大于5
#     #         # 当前页+5 > 总页面
#     #         if (page + plus) > total_page_count:
#     #             start_page = total_page_count - 2 * plus
#     #             end_page = total_page_count + 1
#     #         else:
#     #             start_page = page - plus
#     #             end_page = page + plus + 1
#     #
#     # page_str_list = []
#     # # 首页
#     # page_str_list.append('<li ><a href="?page={}">首页</a></li>'.format(1))
#     # # 上一页
#     # if page > 1:
#     #     prev = '<li><a href="?page={}">上一页</a></li>'.format(page - 1)
#     # else:
#     #     prev = '<li><a href="?page={}">上一页</a></li>'.format(1)
#     # page_str_list.append(prev)
#     #
#     # # 页码
#     # for i in range(start_page, end_page):
#     #     if i == page:
#     #         # 当前页高亮显示
#     #         ele = '<li class="active"><a href="?page={}">{}</a></li>'.format(i, i)
#     #     else:
#     #         ele = '<li><a href="?page={}">{}</a></li>'.format(i, i)
#     #     page_str_list.append(ele)
#     #
#     # # 下一页
#     # if page < total_page_count:
#     #     prev = '<li ><a href="?page={}">下一页</a></li>'.format(page + 1)
#     # else:
#     #     prev = '<li><a href="?page={}">下一页</a></li>'.format(total_page_count)
#     # page_str_list.append(prev)
#     # # 尾页
#     # page_str_list.append('<li ><a href="?page={}">尾页</a></li>'.format(total_page_count))
#     #
#     # search_string = """
#     #  <li>
#     #      <form style="float: left;margin-left: -1px" method="get">
#     #         <input name="page"
#     #                style="position: relative;float: left;display: inline-block;width: 80px;border-radius: 0;"
#     #                type="text" class="form-control" placeholder="页码">
#     #         <button style="border-radius: 0" class="btn btn-default" type="submit">跳转</button>
#     #     </form>
#     # </li>
#     # """
#     # page_str_list.append(search_string)
#     # # 添加mark_safe包，让前端安全读取
#     # page_string = mark_safe("".join(page_str_list))
#
#     return render(request,'pretty_list.html', context)
#
#
# # 继承BootStrapModelForm
# # class PrettyModelForm(BootStrapModelForm):
# #     # 校验POST信息 方法一：
# #     mobile = forms.CharField(
# #         label='号码',
# #         # 正则表达式
# #         validators=[RegexValidator(r'^1\d{10}$','号码格式错误')]
# #     )
# #     class Meta:
# #         model = models.PrettyNum
# #         fields = ["mobile",'price','level','status']
# #         # 另外两种写法
# #         # fields = "__all__" 表示全部字段
# #         # fields = ['level'] 表示除了level的所有字段
# #
# #     # # 继承bootstrap样式
# #     # def __init__(self, *args, **kwargs):
# #     #     super().__init__(*args, **kwargs)
# #     #     # 循环找到widget插件，添加了class="form-control"
# #     #     for name, field in self.fields.items():
# #     #         # 加"placeholder": field.label，输入框显示提示信息
# #     #         field.widget.attrs = {"class": "form-control","placeholder": field.label}
# #
# #     #校验POST信息 方法二：钩子方法，前提已经有这个字段了，Djongo会自动生成clean_XXX
# #     def clean_mobile(self):
# #         txt_mobile = self.cleaned_data['mobile']
# #         # exists方法，在数据中搜索有没有重复的号码，正则不能数据库搜索，所以要用钩子方法
# #         exists = models.PrettyNum.objects.filter(mobile=txt_mobile).exists()
# #         # 号码已存在的钩子方法，在添加页面使用，但是在编辑页面不能用
# #         if exists:
# #             raise ValidationError("号码已存在")
# #         # 验证通过，用户输入的值返回
# #         return txt_mobile
#
# def pretty_add(request):
#     """ 添加靓号 """
#     if request.method == 'GET':
#         form = PrettyModelForm()  # 实例化类得到对象
#         return render(request,'pretty_add.html',{'form':form})
#     # 用户POST提交数据，做数据校验 ，把PrettyModelForm实例化，得到form的数据，放在前端渲染
#     form = PrettyModelForm(data=request.POST)
#     # 如果数据正确则直接返回靓号列表页面
#     if form.is_valid():
#         form.save()
#         return redirect("/pretty/list/")
#     # 校验失败则提示错误信息
#     return render(request,'pretty_add.html',{'form':form})
#
# # 要想靓号可不修改，需要重新定义mobile，只能修改价格，级别，状态，需要重写ModelForm
# # class PrettyEditModelForm(BootStrapModelForm):
# #     # 号码不可修改
# #     # mobile = forms.CharField(disabled=True,label="手机号")
# #     # 校验POST信息 方法一：
# #     mobile = forms.CharField(disabled=True,
# #         label='号码',
# #         # 正则表达式
# #         validators=[RegexValidator(r'^1\d{10}$','号码格式错误')]
# #     )
# #     class Meta:
# #         model = models.PrettyNum
# #         fields = ['mobile','price','level','status']
# #         # 另外两种写法
# #         # fields = "__all__" 表示全部字段
# #         # fields = ['level'] 表示除了level的所有字段
# #
# #     # 继承bootstrap样式
# #     # def __init__(self, *args, **kwargs):
# #     #     super().__init__(*args, **kwargs)
# #     #     # 循环找到widget插件，添加了class="form-control"
# #     #     for name, field in self.fields.items():
# #     #         # 加"placeholder": field.label，输入框显示提示信息
# #     #         field.widget.attrs = {"class": "form-control","placeholder": field.label}
# #
# #     # 校验POST信息 方法二：钩子方法，前提已经有这个字段了，Djongo会自动生成clean_XXX
# #     def clean_mobile(self):
# #         txt_mobile = self.cleaned_data['mobile']
# #         # exists方法，在数据中搜索有没有重复的号码，正则不能数据库搜索，所以要用钩子方法
# #         # 所以这里要加一个排除自己的方法exclude()，获取当前自己的id方法：self.instance.pk
# #         exists = models.PrettyNum.objects.exclude(id=self.instance.pk).filter(mobile=txt_mobile).exists()
# #         # 号码已存在的钩子方法，在添加页面使用，但是在编辑页面不能用
# #         if exists:
# #             raise ValidationError("号码已存在")
# #         # 验证通过，用户输入的值返回
# #         return txt_mobile
# def pretty_edit(request,nid):
#     """ 编辑靓号 """
#     row_object = models.PrettyNum.objects.filter(id=nid).first()
#     if request.method == 'GET':
#         form = PrettyEditModelForm(instance=row_object)
#         return render(request,'pretty_edit.html',{'form':form})
#     # post
#     form = PrettyEditModelForm(data=request.POST,instance=row_object)
#     if form.is_valid():
#         form.save()
#         return redirect("/pretty/list/")
#     return render(request,'pretty_edit.html',{'form':form})
#
# def pretty_delete(request,nid):
#     # filter查询
#     models.PrettyNum.objects.filter(id=nid).delete()
#     return redirect("/pretty/list/")